package com.wuda.servlet.admin;

import com.wuda.bean.Book;
import com.wuda.dao.BookDao;
import net.sf.json.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/admin/updateBookById")
public class UpdateBook extends HttpServlet {
	private final BookDao bookDao = new BookDao();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json; charset=utf8");

		// 获取表单参数
		int bookId = Integer.parseInt(req.getParameter("book_id"));
		String title = req.getParameter("title");
		String author = req.getParameter("author");
		String isbn = req.getParameter("isbn");
		String publisher = req.getParameter("publisher");
		String publishDate = req.getParameter("publish_date");
		int stockQuantity = Integer.parseInt(req.getParameter("stock_quantity"));
		String type = req.getParameter("type");
		String introduce = req.getParameter("introduce");

		// 准备返回参数
		int code = 500;
		String msg = "更新失败";

		// 创建 Book 对象
		Book book = new Book();
		book.setBookId(bookId);
		book.setTitle(title);
		book.setAuthor(author);
		book.setIsbn(isbn);
		book.setPublisher(publisher);
		book.setPublishDate(java.sql.Date.valueOf(publishDate));
		book.setStockQuantity(stockQuantity);
		book.setType(type);
		book.setIntroduce(introduce);

		System.out.println("接收到的修改参数======>" + book);
		// 进行更新操作
		boolean updateSuccess = bookDao.updateBook(book);
		if (updateSuccess) {
			code = 200;
			msg = "更新成功";
		}

		// 返回JSON结果
		JSONObject jsonResult = new JSONObject();
		jsonResult.put("code", code);
		jsonResult.put("msg", msg);

		try (PrintWriter out = resp.getWriter()) {
			out.print(jsonResult);
			out.flush();
		}
	}


	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}

}
